/*import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;*/

import React, { useEffect, useState } from "react";
import web3 from "./web3";
import contract from "./contracts/Crowdfunding";
import 'antd/dist/reset.css';
import { Form, Input, Button, Card, Row, Col, Modal, message, Select } from "antd";

function App() {
  const [projects, setProjects] = useState([]);
  const [title, _setTitle] = useState("");
  const [desc, _setDesc] = useState("");
  const [goal, _setGoal] = useState("");
  const [days, _setDays] = useState("");
  const [contributeAmount, _setContributeAmount] = useState("");
  const [contributeId, _setContributeId] = useState("");
const [withdrawVisible, setWithdrawVisible] = useState(false);
const [withdrawProjectId, setWithdrawProjectId] = useState("");
const [refundVisible, setRefundVisible] = useState(false);
const [refundProjectId, setRefundProjectId] = useState("");
const [cancelVisible, setCancelVisible] = useState(false);
const [cancelProjectId, setCancelProjectId] = useState("");
const [detailVisible, setDetailVisible] = useState(false);
const [detailProjectId, setDetailProjectId] = useState("");
const [detailContent, setDetailContent] = useState("");
const [detailResultVisible, setDetailResultVisible] = useState(false);
const [contribVisible, setContribVisible] = useState(false);
const [contribResultVisible, setContribResultVisible] = useState(false);
const [contribProjectId, setContribProjectId] = useState("");
const [contribList, setContribList] = useState([]);
const [investLogVisible, setInvestLogVisible] = useState(false);
const [investResultVisible, setInvestResultVisible] = useState(false);
const [investAddress, setInvestAddress] = useState("");
const [investText, setInvestText] = useState("");
const [createdVisible, setCreatedVisible] = useState(false);
const [createdResultVisible, setCreatedResultVisible] = useState(false);
const [createdAddress, setCreatedAddress] = useState("");
const [createdText, setCreatedText] = useState("");
const [joinedVisible, setJoinedVisible] = useState(false);
const [joinedResultVisible, setJoinedResultVisible] = useState(false);
const [joinedAddress, setJoinedAddress] = useState("");
const [joinedText, setJoinedText] = useState("");
const [statsVisible, setStatsVisible] = useState(false);
const [statsText, setStatsText] = useState("");
const [accountText, setAccountText] = useState("");
const [accountVisible, setAccountVisible] = useState(false);
const [viewModalVisible, setViewModalVisible] = useState(false);
const [selectedProject, setSelectedProject] = useState(null);



  // 获取所有项目
  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const total = await contract.methods.getTotalProjects().call();
        console.log("总项目数:", total);
        const temp = [];
        for (let i = 1; i <= total; i++) {
          try {
            const p = await contract.methods.getProject(i).call();
            console.log(`项目 ${i}:`, {
              id: p.id,
              title: p.title,
              creator: p.creator,
              status: p.status
            });
            temp.push(p);
          } catch (err) {
            console.error(`获取项目 ${i} 失败:`, err);
          }
        }
        setProjects(temp);
      } catch (e) {
        console.error("加载项目失败：", e);
      }
    };
    fetchProjects();
  }, []);

  // 创建项目
  const handleCreate = async (values) => {
    try {
      if (!values.title?.trim()) {
        message.error("请输入项目标题");
        return;
      }

      if (!values.desc?.trim()) {
        message.error("请输入项目描述");
        return;
      }

      if (!values.goal || isNaN(values.goal) || Number(values.goal) <= 0) {
        message.error("请输入有效的目标金额（大于 0 的数字）");
        return;
      }

      if (!values.days || isNaN(values.days) || parseInt(values.days) <= 0) {
        message.error("请输入有效的持续天数（大于 0 的整数）");
        return;
      }

      const accounts = await window.ethereum.request({ method: "eth_accounts" });
      if (!accounts || accounts.length === 0) {
        message.error("请先连接 MetaMask 钱包");
        return;
      }

      const goalInWei = web3.utils.toWei(values.goal.toString(), "ether");
      const durationInSeconds = (parseInt(values.days) * 24 * 60 * 60).toString(); // 将天数转换为秒数，并转换为字符串

      console.log("创建项目参数:", {
        title: values.title.trim(),
        desc: values.desc.trim(),
        goal: goalInWei,
        days: durationInSeconds
      });

      try {
        // 估算 gas
        const gasEstimate = await contract.methods
          .createProject(
            values.title.trim(),
            values.desc.trim(),
            goalInWei,
            durationInSeconds
          )
          .estimateGas({ from: accounts[0] });

        console.log("Gas 估算结果:", gasEstimate);

        // 增加 20% 的 gas 余量
        const gasLimit = Math.floor(Number(gasEstimate) * 1.2).toString();
        console.log("设置的 Gas Limit:", gasLimit);

        // 获取当前 gas 价格
        const gasPrice = await web3.eth.getGasPrice();
        console.log("当前 Gas Price:", gasPrice);

        const tx = await contract.methods
          .createProject(
            values.title.trim(),
            values.desc.trim(),
            goalInWei,
            durationInSeconds
          )
          .send({ 
            from: accounts[0], 
            gas: gasLimit,
            gasPrice: gasPrice
          });

        console.log("交易发送成功，交易哈希:", tx.transactionHash);
        console.log("等待交易确认...");

        // 等待交易确认
        const receipt = await web3.eth.getTransactionReceipt(tx.transactionHash);
        console.log("交易收据:", receipt);

        if (receipt.status) {
          console.log("✅ 项目创建成功!");
          // 获取项目ID
          const projectId = await contract.methods.getTotalProjects().call();
          console.log("项目ID:", projectId);
        } else {
          throw new Error("交易失败，状态码: " + receipt.status);
        }
      } catch (error) {
        console.error("❌ 创建项目失败:", error);
        if (error.message.includes("gas required exceeds allowance")) {
          throw new Error("Gas 不足，请增加 Gas Limit");
        } else if (error.message.includes("insufficient funds")) {
          throw new Error("账户余额不足");
        } else {
          throw new Error("创建项目失败: " + error.message);
        }
      }
    } catch (err) {
      console.error("创建项目失败:", err);
      message.error("❌ 创建失败：" + err.message);
    }
  };

  // 向项目投资
  const handleContribute = async (values) => {
    try {
      if (!values.projectId || isNaN(values.projectId) || parseInt(values.projectId) <= 0) {
        message.error("请输入有效的项目ID");
        return;
      }

      if (!values.amount || isNaN(values.amount) || Number(values.amount) <= 0) {
        message.error("请输入有效的投资金额");
        return;
      }

      const accounts = await window.ethereum.request({ method: "eth_accounts" });
      if (!accounts || accounts.length === 0) {
        message.error("请先连接 MetaMask 钱包");
        return;
      }

      const amountInWei = web3.utils.toWei(values.amount.toString(), "ether");
      await contract.methods
        .contribute(parseInt(values.projectId))
        .send({ 
          from: accounts[0], 
          value: amountInWei,
          gasPrice: await web3.eth.getGasPrice()
        });
      message.success("✅ 投资成功！");
    } catch (err) {
      console.error("投资失败:", err);
      message.error("❌ 投资失败：" + err.message);
    }
  };
  
  const handleWithdraw = async () => {
  try {
    const accounts = await window.ethereum.request({ method: "eth_accounts" });
    await contract.methods.withdrawFunds(withdrawProjectId).send({ from: accounts[0], gasPrice: await web3.eth.getGasPrice() });
    message.success("✅ 提取成功！");
    setWithdrawVisible(false);
    setWithdrawProjectId("");
  } catch (err) {
    message.error("❌ 提取失败：" + err.message);
  }
};

const handleRefund = async () => {
  try {
    const accounts = await window.ethereum.request({ method: "eth_accounts" });
    if (!accounts || accounts.length === 0) {
      message.error("请先连接 MetaMask 钱包");
      return;
    }

    // 获取项目信息
    const project = await contract.methods.getProject(refundProjectId).call();
    
    // 检查项目状态
    if (Number(project.status) !== 2) { // 2 表示失败状态
      message.error("只有失败的项目才能申请退款");
      return;
    }

    // 检查是否是项目创建者
    if (project.creator.toLowerCase() === accounts[0].toLowerCase()) {
      message.error("项目创建者不能申请退款");
      return;
    }

    // 检查是否已经提取过
    if (project.withdrawn) {
      message.error("项目资金已经被提取过了");
      return;
    }

    // 检查用户是否参与过该项目
    const contribution = await contract.methods.getUserContribution(refundProjectId, accounts[0]).call();
    if (contribution === "0") {
      message.warning("您未参与该项目，无法退款");
      return;
    }

    // 获取当前gas价格
    const gasPrice = await web3.eth.getGasPrice();
    
    // 发送退款交易
    await contract.methods.requestRefund(refundProjectId).send({ 
      from: accounts[0],
      gasPrice: gasPrice
    });
    
    message.success("✅ 退款成功！");
    setRefundVisible(false);
    setRefundProjectId("");
    
    // 重新加载项目列表
    const total = await contract.methods.getTotalProjects().call();
    const temp = [];
    for (let i = 1; i <= total; i++) {
      try {
        const p = await contract.methods.getProject(i).call();
        temp.push(p);
      } catch (err) {
        console.error(`获取项目 ${i} 失败:`, err);
      }
    }
    setProjects(temp);
  } catch (error) {
    console.error("退款失败:", error);
    message.error("❌ 退款失败：" + (error.message || "未知错误"));
  }
};

const handleCancelProject = async () => {
  try {
    const accounts = await window.ethereum.request({ method: "eth_accounts" });
    const project = await contract.methods.getProject(cancelProjectId).call();

    if (project.creator.toLowerCase() !== accounts[0].toLowerCase()) {
      message.error("❌ 只有项目创建者才能取消该项目");
      return;
    }

    if (parseInt(project.status) !== 0) {
      message.warning("⚠️ 当前项目状态不是活跃，无法取消");
      return;
    }

    await contract.methods.cancelProject(cancelProjectId).send({ from: accounts[0], gasPrice: await web3.eth.getGasPrice() });
    message.success("✅ 项目已成功取消！");
    setCancelVisible(false);
    setCancelProjectId("");
  } catch (err) {
    message.error("❌ 取消失败：" + err.message);
  }
};

const handleView = async (projectId) => {
  try {
    console.log("正在获取项目信息，项目ID:", projectId);
    
    // 确保 projectId 是字符串类型
    const projectIdStr = projectId.toString();
    
    const project = await contract.methods.getProject(projectIdStr).call();
    console.log("获取到的项目信息:", project);

    // 转换数值为可读格式
    const formattedProject = {
      ...project,
      goalAmount: web3.utils.fromWei(project.goalAmount, 'ether'),
      currentAmount: web3.utils.fromWei(project.currentAmount, 'ether'),
      deadline: new Date(Number(project.deadline) * 1000).toLocaleString(),
      createdAt: new Date(Number(project.createdAt) * 1000).toLocaleString(),
      status: ['活跃中', '成功', '失败', '已提取'][Number(project.status)]
    };

    setSelectedProject(formattedProject);
    setViewModalVisible(true);
  } catch (err) {
    console.error("获取项目详情失败:", err);
    message.error("❌ 获取失败：" + err.message);
  }
};

const handleViewContributors = async () => {
  try {
    if (!contribProjectId) {
      message.error("请输入项目ID");
      return;
    }

    const contributors = await contract.methods.getProjectContributors(contribProjectId).call();
    const project = await contract.methods.getProject(contribProjectId).call();
    
    let result = `项目 "${project.title}" 的投资者列表：\n\n`;
    
    if (contributors.length === 0) {
      result += "暂无投资者";
    } else {
      for (let i = 0; i < contributors.length; i++) {
        const contribution = await contract.methods.getUserContribution(contribProjectId, contributors[i]).call();
        result += `${i + 1}. ${contributors[i]}\n   投资金额: ${web3.utils.fromWei(contribution, 'ether')} ETH\n\n`;
      }
    }
    
    setContribList(contributors);
    setContribVisible(false);
    setContribResultVisible(true);
  } catch (err) {
    console.error("获取投资者失败:", err);
    message.error("❌ 获取失败：" + err.message);
  }
};

const handleCheckInvestLog = async () => {
  try {
    let address = investAddress.trim();
    if (!address) {
      const accounts = await window.ethereum.request({ method: "eth_accounts" });
      address = accounts[0];
    }

    const participated = await contract.methods.getUserParticipatedProjects(address).call();
    if (participated.length === 0) {
      setInvestText("该用户尚未参与任何项目");
    } else {
      let result = `用户 ${address} 的投资记录：\n\n`;
      let total = '0';
      
      for (let i = 0; i < participated.length; i++) {
        const id = participated[i];
        const project = await contract.methods.getProject(id).call();
        const amount = await contract.methods.getUserContribution(id, address).call();
        
        // 直接使用字符串，不进行任何数字转换
        result += `[项目 ${id}] ${project.title}\n`;
        result += `   投资金额: ${web3.utils.fromWei(amount, "ether")} ETH\n`;
        result += `   项目状态: ${['活跃中', '成功', '失败', '已提取'][Number(project.status)]}\n\n`;
      }
      
      // 分别显示每个项目的投资金额，不计算总和
      result += `\n注意：由于技术限制，无法显示总投资金额。请查看上方各项目的具体投资金额。`;
      
      setInvestText(result);
    }

    setInvestLogVisible(false);
    setInvestResultVisible(true);
  } catch (err) {
    message.error("❌ 获取失败：" + err.message);
  }
};

const handleViewCreatedProjects = async () => {
  try {
    let address = createdAddress.trim();
    if (!address) {
      const accounts = await window.ethereum.request({ method: "eth_accounts" });
      address = accounts[0];
    }

    const createdProjects = await contract.methods.getUserCreatedProjects(address).call();
    if (createdProjects.length === 0) {
      setCreatedText("该用户尚未创建任何项目");
    } else {
      let result = `用户 ${address} 创建的项目：\n\n`;
      let successful = 0;
      
      for (let i = 0; i < createdProjects.length; i++) {
        const id = createdProjects[i];
        const project = await contract.methods.getProject(id).call();
        
        // 直接使用字符串，不进行任何数字转换
        result += `${i + 1}. 项目 "${project.title}"\n`;
        result += `   描述: ${project.description}\n`;
        result += `   目标金额: ${web3.utils.fromWei(project.goalAmount, "ether")} ETH\n`;
        result += `   已筹金额: ${web3.utils.fromWei(project.currentAmount, "ether")} ETH\n`;
        result += `   状态: ${['活跃中', '成功', '失败', '已提取'][Number(project.status)]}\n`;
        result += `   投资者数: ${project.contributorsCount}\n\n`;
        
        if (project.status === "1" || project.status === "3") {
          successful++;
        }
      }
      
      result += `\n总计创建项目: ${createdProjects.length} 个\n`;
      result += `成功项目数: ${successful} 个（成功率 ${((successful * 100) / createdProjects.length).toFixed(1)}%）\n`;
      result += `\n注意：由于技术限制，无法显示总目标金额和总已筹金额。请查看上方各项目的具体金额。`;
      
      setCreatedText(result);
    }

    setCreatedVisible(false);
    setCreatedResultVisible(true);
  } catch (err) {
    message.error("❌ 获取失败：" + err.message);
  }
};

const handleViewJoinedProjects = async () => {
  try {
    let address = joinedAddress.trim();
    if (!address) {
      const accounts = await window.ethereum.request({ method: "eth_accounts" });
      address = accounts[0];
    }

    const joined = await contract.methods.getUserParticipatedProjects(address).call();
    if (joined.length === 0) {
      setJoinedText("该用户尚未参与任何项目");
    } else {
      let result = `用户 ${address} 参与的项目：\n\n`;
      
      for (let i = 0; i < joined.length; i++) {
        const id = joined[i];
        const project = await contract.methods.getProject(id).call();
        const contribution = await contract.methods.getUserContribution(id, address).call();
        
        // 直接使用字符串，不进行任何数字转换
        result += `${i + 1}. 项目 "${project.title}"\n`;
        result += `   描述: ${project.description}\n`;
        result += `   投资金额: ${web3.utils.fromWei(contribution, "ether")} ETH\n`;
        result += `   项目目标: ${web3.utils.fromWei(project.goalAmount, "ether")} ETH\n`;
        result += `   当前进度: ${web3.utils.fromWei(project.currentAmount, "ether")} ETH\n`;
        result += `   状态: ${['活跃中', '成功', '失败', '已提取'][Number(project.status)]}\n\n`;
      }
      
      result += `\n总计参与项目: ${joined.length} 个\n`;
      result += `\n注意：由于技术限制，无法显示总投资金额。请查看上方各项目的具体投资金额。`;
      
      setJoinedText(result);
    }

    setJoinedVisible(false);
    setJoinedResultVisible(true);
  } catch (err) {
    message.error("❌ 获取失败：" + err.message);
  }
};

const handleAccountInfo = async () => {
  try {
    const accounts = await window.ethereum.request({ method: "eth_accounts" });
    if (!accounts || accounts.length === 0) {
      message.error("请先连接 MetaMask 钱包");
      return;
    }
    const account = accounts[0];
    const balance = await web3.eth.getBalance(account);
    const chainId = await web3.eth.getChainId();
    
    // 根据 chainId 获取网络名称
    let networkName = "未知";
    switch (chainId) {
      case 1:
        networkName = "以太坊主网";
        break;
      case 3:
        networkName = "Ropsten 测试网";
        break;
      case 4:
        networkName = "Rinkeby 测试网";
        break;
      case 5:
        networkName = "Goerli 测试网";
        break;
      case 42:
        networkName = "Kovan 测试网";
        break;
      case 11155111:
        networkName = "Sepolia 测试网";
        break;
      default:
        networkName = `未知网络 (Chain ID: ${chainId})`;
    }
    
    const info = `📊 账户信息：
地址: ${account}
余额: ${web3.utils.fromWei(balance, 'ether')} ETH
网络: ${networkName}
链ID: ${chainId}`;
    
    setAccountText(info);
    setAccountVisible(true);
  } catch (error) {
    console.error("获取账户信息失败:", error);
    message.error("获取账户信息失败：" + error.message);
  }
};

  return (
    <div style={{ padding: "20px" }}>
<Card title="📝 创建新项目" style={{ marginBottom: "24px" }}>
  <Form
    layout="vertical"
    onFinish={handleCreate}
  >
    <Form.Item name="title" label="标题" rules={[{ required: true }]}>
      <Input placeholder="输入项目标题" />
    </Form.Item>
    <Form.Item name="desc" label="描述" rules={[{ required: true }]}>
      <Input placeholder="输入项目描述" />
    </Form.Item>
    <Form.Item name="goal" label="目标金额 (ETH)" rules={[{ required: true }]}>
      <Input placeholder="如：1" />
    </Form.Item>
    <Form.Item name="days" label="持续天数" rules={[{ required: true }]}>
      <Input placeholder="如：30" />
    </Form.Item>
    <Button type="primary" htmlType="submit">
      创建项目
    </Button>
  </Form>
</Card>


     <h2 style={{ marginTop: "32px" }}>📋 所有众筹项目</h2>
<Row gutter={[16, 16]}>
  {projects.map((p, index) => (
    <Col xs={24} sm={12} md={12} key={index}>
      <Card title={`📌 ${p.title || "未命名项目"}`} variant="outlined">
        <p><strong>描述:</strong> {p.description || "无"}</p>
        <p><strong>目标:</strong> {p.goalAmount ? web3.utils.fromWei(p.goalAmount, "ether") : "未知"} ETH</p>
        <p><strong>已筹:</strong> {p.currentAmount ? web3.utils.fromWei(p.currentAmount, "ether") : "未知"} ETH</p>
        <p><strong>状态:</strong> {['活跃中', '成功', '失败', '已提取'][Number(p.status)] || "未知"}</p>
      </Card>
    </Col>
  ))}
</Row>


<Card title="💰 向项目投资" style={{ marginTop: 32 }}>
  <Form
    layout="vertical"
    onFinish={handleContribute}
  >
    <Form.Item name="projectId" label="项目ID" rules={[{ required: true, message: "请输入项目ID" }]}>
      <Input placeholder="输入项目编号" />
    </Form.Item>
    <Form.Item name="amount" label="投资金额（ETH）" rules={[{ required: true, message: "请输入金额" }]}>
      <Input placeholder="如：0.5" />
    </Form.Item>
    <Button type="primary" htmlType="submit">投资</Button>
  </Form>
</Card>


<Card title="🏦 提取项目资金" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setWithdrawVisible(true)}>我要提取</Button>

  <Modal
    title="提取资金"
    open={withdrawVisible}
    onOk={handleWithdraw}
    onCancel={() => setWithdrawVisible(false)}
    okText="确认提取"
    cancelText="取消"
  >
    <Input
      placeholder="请输入要提取的项目ID"
      value={withdrawProjectId}
      onChange={(e) => setWithdrawProjectId(e.target.value)}
    />
  </Modal>
</Card>

<Card title="🔄 申请退款" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setRefundVisible(true)}>申请退款</Button>

  <Modal
    title="输入退款项目ID"
    open={refundVisible}
    onOk={handleRefund}
    onCancel={() => setRefundVisible(false)}
    okText="确认退款"
    cancelText="取消"
  >
    <Input
      placeholder="请输入项目ID"
      value={refundProjectId}
      onChange={(e) => setRefundProjectId(e.target.value)}
    />
  </Modal>
</Card>

<Card title="❌ 取消项目" style={{ marginTop: 32 }}>
  <Button type="primary" danger onClick={() => setCancelVisible(true)}>
    我要取消
  </Button>

  <Modal
    title="取消项目"
    open={cancelVisible}
    onOk={handleCancelProject}
    onCancel={() => setCancelVisible(false)}
    okText="确认取消"
    cancelText="关闭"
  >
    <Input
      placeholder="请输入要取消的项目ID"
      value={cancelProjectId}
      onChange={(e) => setCancelProjectId(e.target.value)}
    />
  </Modal>
</Card>

<Card title="📋 查看项目详情" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setDetailVisible(true)}>查看详情</Button>

  <Modal
    title="查看项目详情"
    open={detailVisible}
    onOk={() => handleView(detailProjectId)}
    onCancel={() => setDetailVisible(false)}
    okText="查看"
    cancelText="取消"
  >
    <Form.Item
      label="项目ID"
      name="projectId"
      rules={[{ required: true, message: '请输入项目ID' }]}
    >
      <Input
        value={detailProjectId}
        onChange={(e) => setDetailProjectId(e.target.value)}
        placeholder="请输入项目ID"
      />
    </Form.Item>
  </Modal>

  <Modal
    title="项目详情"
    open={detailResultVisible}
    onOk={() => setDetailResultVisible(false)}
    onCancel={() => setDetailResultVisible(false)}
    footer={null}
  >
    <pre>{detailContent}</pre>
  </Modal>
</Card>

<Card title="👥 查看项目投资者" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setContribVisible(true)}>查看投资者</Button>

  <Modal
    title="请输入项目ID"
    open={contribVisible}
    onOk={handleViewContributors}
    onCancel={() => setContribVisible(false)}
    okText="确认"
    cancelText="取消"
  >
    <Input
      placeholder="项目ID"
      value={contribProjectId}
      onChange={(e) => setContribProjectId(e.target.value)}
    />
  </Modal>

  <Modal
    title="投资者列表"
    open={contribResultVisible}
    onOk={() => setContribResultVisible(false)}
    onCancel={() => setContribResultVisible(false)}
    footer={null}
  >
    {contribList.length > 0 ? (
      <ul>
        {contribList.map((addr, idx) => (
          <li key={idx}>{addr}</li>
        ))}
      </ul>
    ) : (
      <p>该项目目前暂无投资者。</p>
    )}
  </Modal>
</Card>

<Card title="🔍 查看用户投资记录" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setInvestLogVisible(true)}>查看投资记录</Button>

  <Modal
    title="请输入地址（留空查看当前账户）"
    open={investLogVisible}
    onOk={handleCheckInvestLog}
    onCancel={() => setInvestLogVisible(false)}
    okText="查看"
    cancelText="取消"
  >
    <Input
      placeholder="0x..."
      value={investAddress}
      onChange={(e) => setInvestAddress(e.target.value)}
    />
  </Modal>

  <Modal
    title="用户投资记录"
    open={investResultVisible}
    onCancel={() => setInvestResultVisible(false)}
    footer={null}
  >
    <pre>{investText || "暂无记录"}</pre>
  </Modal>
</Card>

<Card title="📊 查看用户创建的项目" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setCreatedVisible(true)}>查看创建的项目</Button>

  <Modal
    title="请输入地址（留空查看当前账户）"
    open={createdVisible}
    onOk={handleViewCreatedProjects}
    onCancel={() => setCreatedVisible(false)}
    okText="查看"
    cancelText="取消"
  >
    <Input
      placeholder="0x..."
      value={createdAddress}
      onChange={(e) => setCreatedAddress(e.target.value)}
    />
  </Modal>

  <Modal
    title="用户创建的项目"
    open={createdResultVisible}
    onCancel={() => setCreatedResultVisible(false)}
    footer={null}
  >
    <pre>{createdText}</pre>
  </Modal>
</Card>

<Card title="📈 查看用户参与的项目" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={() => setJoinedVisible(true)}>查看参与的项目</Button>

  <Modal
    title="请输入地址（留空查看当前账户）"
    open={joinedVisible}
    onOk={handleViewJoinedProjects}
    onCancel={() => setJoinedVisible(false)}
    okText="查看"
    cancelText="取消"
  >
    <Input
      placeholder="0x..."
      value={joinedAddress}
      onChange={(e) => setJoinedAddress(e.target.value)}
    />
  </Modal>

  <Modal
    title="参与的项目"
    open={joinedResultVisible}
    onCancel={() => setJoinedResultVisible(false)}
    footer={null}
  >
    <pre>{joinedText}</pre>
  </Modal>
</Card>

<Card title="💳 查看账户信息" style={{ marginTop: 32 }}>
  <Button type="primary" onClick={handleAccountInfo}>查看账户信息</Button>

  <Modal
    title="账户信息"
    open={accountVisible}
    onCancel={() => setAccountVisible(false)}
    footer={null}
  >
    <pre>{accountText}</pre>
  </Modal>
</Card>

<Modal
  title="项目详情"
  open={viewModalVisible}
  onCancel={() => setViewModalVisible(false)}
  footer={null}
  width={600}
>
  {selectedProject && (
    <div style={{ padding: '20px' }}>
      <h2>{selectedProject.title}</h2>
      <p style={{ marginBottom: '20px' }}>{selectedProject.description}</p>
      
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
        <div>
          <p><strong>项目ID:</strong> {selectedProject.id}</p>
          <p><strong>创建者:</strong> {selectedProject.creator}</p>
          <p><strong>目标金额:</strong> {selectedProject.goalAmount} ETH</p>
          <p><strong>当前金额:</strong> {selectedProject.currentAmount} ETH</p>
          <p><strong>投资者数量:</strong> {selectedProject.contributorsCount}</p>
        </div>
        <div>
          <p><strong>创建时间:</strong> {selectedProject.createdAt}</p>
          <p><strong>截止时间:</strong> {selectedProject.deadline}</p>
          <p><strong>状态:</strong> {selectedProject.status}</p>
          <p><strong>是否已提取:</strong> {selectedProject.withdrawn ? '是' : '否'}</p>
        </div>
      </div>

      <div style={{ marginTop: '20px', textAlign: 'right' }}>
        <Button onClick={() => setViewModalVisible(false)}>关闭</Button>
      </div>
    </div>
  )}
</Modal>

    </div>
    
    
  );
}

export default App;
